<template>
  <el-dialog
    :title="title"
    :visible="showDialog"
    @close="resetFormDate"
  >
    <!-- <div slot="title" class="title">添加部门</div> -->
    <el-form ref="deptForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="getEmployeesList">
          <el-option v-for="(item,index) in employeesList" :key="index" :label="item.username" :value="item.username " />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" type="textarea" style="width:80%;" placeholder="1-300字符" :rows="3" />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="resetFormDate">取消</el-button>
        <el-button type="primary" size="small" @click="btnOk">确认</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script>

import { getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'

export default {
  name: 'AddDept',
  // model: {
  //   prop: 'showDialog',
  //   event: 'showDialog'
  // },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    // 检查部门名称是否重复
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // 同级部门下(要排除自己) 名字不能相同
        isRepeat = depts.filter(item => item.pid === this.treeNode.pid && item.id !== this.treeNode.id).some(item => item.name === value)
      } else {
        isRepeat = depts.filter(item => item.pid === this.treeNode.id).some(item => item.name === value)
      }
      isRepeat ? callback(new Error(`同级部门下已经存在"${value}"这个部门了！`)) : callback()
    }
    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let isRepeat = false
      if (this.formData.id) {
        // 先排除自己  再跟别人比
        isRepeat = depts.filter(item => item.id !== this.treeNode.id).some(item => item.code === value && value)
      } else {
        // 有可能历史数据没有code，value为空，则返回true    因此强制value不能为空
        isRepeat = depts.some(item => item.code === value && value)
      }
      isRepeat ? callback(new Error(`组织架构下已经存在"${value}"这个编码了！`)) : callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [{ required: true, trigger: 'blur', message: '部门名称不能为空！' },
          { min: 1, max: 15, trigger: 'blur', message: '部门名称长度为1-15位' },
          { validator: checkNameRepeat, trigger: 'blur' }],
        code: [{ required: true, trigger: 'blur', message: '部门编码不能为空！' },
          { min: 1, max: 50, trigger: 'blur', message: '部门编码长度为1-50位' },
          { validator: checkCodeRepeat, trigger: 'blur' }],
        manager: [{ required: true, trigger: 'blur', message: '部门负责人不能为空！' }],
        introduce: [{ required: true, trigger: 'blur', message: '部门介绍不能为空！' },
          { min: 1, max: 300, trigger: 'blur', message: '部门结束长度为1-300位' }]
      },
      employeesList: [] // 简单员工列表

    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '添加子部门'
    }
  },
  methods: {
    // 获取简单员工列表
    async getEmployeesList() {
      this.employeesList = await getEmployeeSimple()
    },
    // 点击确认 手动验证表单+添加部门+根据ID修改部门详情
    btnOk() {
      // 手动验证表单
      this.$refs.deptForm.validate(async isok => {
        if (isok) {
          if (this.formData.id) {
            // 发请求 根据ID修改部门详情
            await updateDepartments(this.formData)
          } else {
            // 发请求 添加部门
            await addDepartments({ ...this.formData, pid: this.treeNode.id })
          }
          this.$emit('addDepts')
          // 手动关闭dialog  会自动触发dialog的close事件 因此重置表单
          this.$emit('update:showDialog', false)
          // this.$emit('showDialog', false)   使用v-model
          // this.$refs.deptForm.resetFields()  重置表单
        }
      })
    },
    // 点击取消 重置表单
    resetFormDate() {
      // 因为resetFields只能重置表单上的数据 其他数据不能重置eg：id等
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$emit('update:showDialog', false)
      this.$refs.deptForm.resetFields()
    },
    // 根据ID查询部门详情
    async getDepartDetail(id) {
      this.formData = await getDepartDetail(id)
    }

  }
}
</script>

<style scoped lang="scss">
.el-dialog__wrapper ::v-deep{
  .el-dialog__header{
    background-color: rgb(7, 123, 255);
    .el-dialog__title,.el-dialog__headerbtn .el-dialog__close{
        color:#fff;
      }
  }
  .el-textarea__inner{
    resize:none
  }
}
</style>
